<template>
  <div class="app-container">

    <u-page title="模块管理">
      <div slot="header">
        <el-button type="primary" icon="el-icon-edit" @click="hdlOpen(newForm)">
          {{ textMap['create'] }}
        </el-button>
      </div>

      <div style="margin-bottom: 20px">
        <el-alert title="温馨提示" type="success" show-icon :closable="false">
          <span style="font-weight: bold; font-size: 12px;">
            短信模板审核需要提交到短信服务商审核，非工作时间，审核时间可能会延长。
          </span>
        </el-alert>
      </div>

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="listQuery.type" placeholder="模板类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="通知" :value="1" />
              <el-option label="验证码" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="listQuery.name" placeholder="关键词" clearable />
          </el-form-item>
          <el-form-item label="模板ID" prop="templateId">
            <el-input v-model="listQuery.templateId" placeholder="模板ID" clearable />
          </el-form-item>
          <el-form-item label="操作人" prop="createdBy">
            <el-input v-model="listQuery.createdBy" placeholder="关键词" clearable style="width: 160px" maxlength="11" show-word-limit />
          </el-form-item>
          <el-form-item label="操作时间">
            <u-date-time-picker v-model="searchDate" @change="changeSearchDate" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <u-status v-model="listQuery.status" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <u-table
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button type="text" @click="hdlEdit(row)">编辑</el-button>
              <el-button type="text" @click="hdlDelete(row.id, row.name)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>

    </u-page>

    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" @confirm="dialogStatus==='create'?hdlCreate():hdlUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-width="80px">

        <el-form-item prop="type" label="短信类型">
          <el-select v-model="dataForm.type" placeholder="短信类型" clearable>
            <el-option label="通知" :value="1" />
            <el-option label="验证码" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item prop="templateId" label="模板ID">
          <el-input v-model="dataForm.templateId" placeholder="模版ID" clearable maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item prop="name" label="模板名称">
          <el-input v-model="dataForm.name" placeholder="模版名称，例：订单创建成功通知（自定义）" clearable maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item prop="content" label="模板内容">
          <el-input v-model="dataForm.content" type="textarea" :rows="5" placeholder="短信内容字数（含签名）超过70个字符，将每67个字符为1条进行计费（建议号码和链接前后添加空格，以方便客户直接点击和拨打电话）" clearable maxlength="500" show-word-limit />
          <u-tip-info :title="`计费说明：当前${wordCount()}字，预计发送条数约为${lineCount()}（实际发送时，签名、变量长度会影响总字数）。`" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
    </u-dialog>

  </div>
</template>
<script>

export default {
  data() {
    return {
      api: this.$u.api.PluginsSmsTemplate,
      // 表格
      columns: [
        {
          prop: 'templateId',
          label: '模板ID'
        },
        {
          prop: 'name',
          label: '模板名称'
        },
        {
          prop: 'content',
          label: '模板内容'
        },
        {
          prop: 'type',
          label: '模板类型',
          render: (h, params) => {
            const { type } = params.row
            const title = type === 1 ? '通知' : '验证码'
            return h('el-tag', title)
          }
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status) {
              return h('el-tag', { props: { type: 'success' }}, '已启用')
            } else {
              return h('el-tag', { props: { type: 'danger' }}, '禁用')
            }
          }
        },
        {
          prop: 'createdBy',
          label: '操作人'
        },
        {
          prop: 'createdAt',
          label: '操作时间',
          timestamp: true
        }
      ],

      list: [],
      listLoading: false,
      listOptions: {
        mutiSelect: true
      },
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        totalCount: 1,
        beginTime: '',
        endTime: '',
        createdBy: '',
        name: '',
        type: ''
      },

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑模板',
        create: '新增模板'
      },
      dataForm: {},
      rules: {
        name: [
          { required: true, message: '请输入模板名称,便于后台搜索查询选择', trigger: ['blur'] }
        ],
        templateId: [
          { required: true, message: '服务商提供的模板ID', trigger: ['blur'] }
        ],
        type: [
          { required: true, message: '请选择模板类型', trigger: ['blur'] }
        ],
        content: [
          { required: true, message: '请输入短信内容', trigger: ['blur'] }
        ]
      },
      // 删除选中数据
      selectData: [],
      newForm: {
        type: 1,
        status: true
      },
      // 时间范围
      searchDate: []
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    // 计算字数
    wordCount() {
      const { content } = this.dataForm
      if (content) {
        return content.length
      } else {
        return 0
      }
    },
    // 计算行数
    lineCount() {
      const totalLength = this.wordCount()
      if (totalLength <= 70) {
        return `1条`
      } else if (totalLength <= 500) {
        // 按照67字拆分成多条短信
        const smsCount = Math.ceil(totalLength / 67)
        return `${smsCount}条`
      } else {
        return `长度超过500字上限`
      }
    }
  }
}
</script>
